﻿using System;
using System.Collections.Generic;

using System.Windows;
using System.Windows.Controls;

using System.Windows.Input;
using System.Windows.Navigation;

using EagleJournal.Controls;
using EagleJournal.Components;

using EagleJournalBE.Util;
using EagleJournalBE.Database.Tables;

namespace EagleJournal
{
	public partial class PanelClientEdit : UserControl
	{
        public static readonly  DependencyProperty
            CreateModeProperty          = DependencyProperty.Register("CreateMode", typeof(bool), typeof(PanelClientEdit));
        public                  bool
            CreateMode
        {
            get { return (bool)this.GetValue(CreateModeProperty); }
            set { this.SetValue(CreateModeProperty, value); }
        }

        public static readonly  RoutedEvent
            InvokeEditCompleteEvent     = EventManager.RegisterRoutedEvent("InvokeEditComplete", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(PanelClientEdit));
        public event            RoutedEventHandler
            InvokeEditComplete
        {
            add     { this.AddHandler(InvokeEditCompleteEvent, value); }
            remove  { this.RemoveHandler(InvokeEditCompleteEvent, value); }
        }

        int                 updateID;
        TableClient         clients;
        TableClientContact  contact;

		public              PanelClientEdit                 ()
		{
			this.InitializeComponent();
		}

        private     void    UserControl_IsVisibleChanged    (object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.Visibility == Visibility.Visible)
            {
                if (this.CreateMode)
                {
                    this.ButtonCreate.Content = "Create";
                }
                else
                {
                    this.ButtonCreate.Content = "Update";
                }

                FocusHelper.Focus(this.TextName);
            }
        }

        private     void    ButtonDiscard_Click             (object sender, RoutedEventArgs e)
        {
            this.ClearData();

            this.RaiseEvent(new RoutedEventArgs(InvokeEditCompleteEvent));
        }
        private     void    ButtonCreate_Click              (object sender, RoutedEventArgs e)
        {
            int clientContactIDBase;

            // create/update the contact's info
            if (this.CreateMode)
            {
                int ID = ScanAvailableID();
                clientContactIDBase = ID;

                clients.Create(
                    ID, 
                    new List<object>() { ID, this.TextName.Text }
                );
            }
            else
            {
                clientContactIDBase = updateID;

                clients.Update(
                    updateID, 
                    new List<object>() { updateID, this.TextName.Text }
                );
            }

            // then remove the client's contact then add them (kinna brutal, i know)
            this.contact.Filter("clientContactID = " + clientContactIDBase);
            foreach (List<object> row in this.contact.TableData)
            {
                this.contact.Remove((int)row[0]);
            }

            bool errorFound = false;
            string details  = string.Empty;

            // finally add the client's contacts
            int index = clientContactIDBase * 1000;
            foreach (ListClientContact contact in this.DataContact.Items)
            {
                long contactValue;

                if (!long.TryParse((string)contact.Content, out contactValue))
                {
                    errorFound  = true;
                    details     += string.Format("\n>{0}: \t{1}", contact.ClientContactType, contact.Content);

                    continue;
                }
                // eto yung problema
                this.contact.Create(
                    index,
                    new List<object>() { index, clientContactIDBase, contact.ClientContactType, Convert.ToString(contactValue), true }
                );

                index++;
            }

            if (errorFound)
                EagleMessageBox.ShowMessageBox("Input error", "Contact value(s) specified is not in a valid format! They will not be included in the database.\n" + details, MessageBoxImage.Warning, MessageBoxButton.OK);
            else
                this.RaiseEvent(new RoutedEventArgs(InvokeEditCompleteEvent));
        }

        private     void    ButtonAdd_Click                 (object sender, RoutedEventArgs e)
        {
            this.DataContact.Items.Add(new ListClientContact() { ClientContactEditMode = true });

            this.DataContact.SelectedIndex = this.DataContact.Items.Count - 1;
        }

        public      void    LinkClientTable                 (TableClient clients, TableClientContact contact)
        {
            this.clients = clients;
            this.contact = contact;
        }

        public      void    ClearData                       ()
        {
            this.TextName.Text = string.Empty;
            this.DataContact.Items.Clear();
        }
        public      void    PassData                        (int ID, string name, List<ClientContact> contact)
        {
            this.updateID       = ID;
            this.TextName.Text  = name;

            foreach (ClientContact row in contact)
            {
                ListClientContact list = new ListClientContact()
                {
                    ClientContactEditMode   = true,
                    ClientContactType       = row.Type,
                    Content                 = row.Value,
                };

                this.DataContact.Items.Add(list);
            }
        }

        private     void    TextName_TextChanged            (object sender, TextChangedEventArgs e)
        {
            if (this.TextName.Text.Length > 0)
                this.ButtonCreate.IsEnabled = true;
            else
                this.ButtonCreate.IsEnabled = false;
        }

        private     int     ScanAvailableID                 ()
        {
            int returnIndex = 1;
            for (int i = 0; i < this.clients.TableData.Count; i++)
            {
                returnIndex++;

                if (i < (this.clients.TableData.Count - 2))
                {
                    if (((int)this.clients.TableData[i][0] + 1) != ((int)this.clients.TableData[i + 1][0]))
                    {
                        return returnIndex;
                    }
                }
            }

            return returnIndex;
        }
	}
}
